package cn.springmix.core.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author xufeng
 * @description: 全局线程池
 * @date 2022-04-20 11:33
 */
@Configuration
public class ThreadPoolConfig {

    @Bean("dmpExecutor")
    @Primary
    public ThreadPoolTaskExecutor dmpExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        int cpuCoreCount = Runtime.getRuntime().availableProcessors();
        // 设置核心线程数
        executor.setCorePoolSize(cpuCoreCount);
        // 设置最大线程数
        executor.setMaxPoolSize(cpuCoreCount*2);
        // 设置队列容量
        executor.setQueueCapacity(cpuCoreCount*200);
        // 设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(60);
        // 设置默认线程名称
        executor.setThreadNamePrefix("dmp-executor-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
}
